package com.itheima.nio.tomcat.domain;

import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

public class HttpResponse {

    private String version;
    private String status;
    private String desc;
    private List<Header> headers = new ArrayList<>();
    private String contentType;
    private SelectionKey selectionKey;
    private HttpRequest httpRequest;
    public static final String WEB_APP_PATH = "itheima-nio-tomcat-1\\webapp";

    public HttpResponse(SelectionKey selectionKey){
        this.selectionKey = selectionKey;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    public List<Header> getHeaders() {
        return headers;
    }

    public void setHeaders(List<Header> headers) {
        this.headers = headers;
    }

    public String getContentType() {
        return contentType;
    }

    public void setContentType(String contentType) {
        Header header = new Header();
        header.setName("Content-Type");
        header.setValue(contentType);
        headers.add(header);
        this.contentType = contentType;
    }

    public SelectionKey getSelectionKey() {
        return selectionKey;
    }

    public void setSelectionKey(SelectionKey selectionKey) {
        this.selectionKey = selectionKey;
    }

    public HttpRequest getHttpRequest() {
        return httpRequest;
    }

    public void setHttpRequest(HttpRequest httpRequest) {
        this.httpRequest = httpRequest;
    }

    public void sendStaticResource(){
        this.version = "Http/1.1";
        String requestURI = httpRequest.getRequestURI();
        if ("".equals(requestURI) || requestURI == null){
            return;
        }
        //浏览器访问只输入ip地址，则WEB_APP_PATH = "itheima-socket-tomcat\\webapp\\"
        //此时webapp后面只有一个/(一个/=两个\\)因此判断的是文件夹路径，webapp确实存在
        //则File对象创建成功
        File file = new File(WEB_APP_PATH + requestURI);
        if (file.exists()){
            this.status = "200";
            this.desc = "OK";
        } else {
            this.status = "404";
            this.desc = "NOT FOUND";
        }
        String responseLine = this.version + " " + this.status + " " + this.desc + "\r\n";
//        this.setContentType("text/html;charset=UTF-8");
//        this.setContentType("image/jpeg");
        if (!this.status.equals("404")){
            if (requestURI.endsWith("txt") || requestURI.equals("/")){
                this.setContentType("text/html;charset=UTF-8");
            } else if (requestURI.endsWith(".jpg")){
                this.setContentType("image/jpeg");
            } else if (requestURI.endsWith(".ico")){
                this.setContentType("image/x-icon");
            }
        } else {
            this.setContentType("text/html;charset=UTF-8");
        }

        StringBuilder stringBuilder = new StringBuilder();
        for (Header header : headers){
            stringBuilder.append(header.getName()).append(": ").append(header.getValue()).append("\r\n");
        }
        String responseHeader = stringBuilder.toString();
        String emptyLine = "\r\n";
        String responseLineAndHeaderAndEmptyLine = responseLine + responseHeader + emptyLine;
        try{
            SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
            ByteBuffer byteBuffer = ByteBuffer.wrap(responseLineAndHeaderAndEmptyLine.getBytes("UTF-8"));
            socketChannel.write(byteBuffer);
//            String content = "你好，NIO Http服务器........";
//            ByteBuffer byteBuffer1 = ByteBuffer.wrap(content.getBytes("UTF-8"));
            ByteBuffer byteBuffer1 = ByteBuffer.wrap(getContent());
            socketChannel.write(byteBuffer1);
            socketChannel.close();
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    public byte[] getContent(){
        try{
            if (this.status.equals("200")){
                String requestURI = httpRequest.getRequestURI();
//                if (requestURI.endsWith("favicon.ico")){
//                    return "无此图标文件".getBytes("UTF-8");
//                } else {
//            FileInputStream fileInputStream = new FileInputStream(WEB_APP_PATH + "\\html\\1.txt");
//            FileInputStream fileInputStream = new FileInputStream(WEB_APP_PATH + "\\image\\mv.jpg");
                if (requestURI.equals("/")){
                    FileInputStream fileInputStream = new FileInputStream(WEB_APP_PATH + "/html/index.txt");
                    byte[] bytes = IOUtils.toByteArray(fileInputStream);
                    return bytes;
                } else {
                    FileInputStream fileInputStream = new FileInputStream(WEB_APP_PATH + requestURI);
                    byte[] bytes = IOUtils.toByteArray(fileInputStream);
                    return bytes;
                }

//                }
            } else {
                return "对不起，不存在你要访问的服务器资源".getBytes("UTF-8");
            }

        } catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public void write(String content) {
        this.version = "HTTP/1.1";
        this.status = "200";
        this.desc = "OK";
        String responseLine = this.version + this.status + this.desc + "\r\n";
        StringBuilder stringBuilder = new StringBuilder();
        for (Header header : headers){
            stringBuilder.append(header.getName()).append(": ").append(header.getValue()).append("\r\n");
        }
        String responseHeader = stringBuilder.toString();
        String responseEmptyLine = "\r\n";
        String responseLineAndHeaderAndEmptyLine = responseLine + responseHeader + responseEmptyLine;
        try {
            ByteBuffer byteBuffer = ByteBuffer.wrap(responseLineAndHeaderAndEmptyLine.getBytes("UTF-8"));
            SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
            socketChannel.write(byteBuffer);
            socketChannel.write(ByteBuffer.wrap(content.getBytes("UTF-8")));
            socketChannel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
